// pages/goods/goodsdetail/goodsdetail.js
import load from '../../templates/loader/loader.js'
import api from '../../../api/api.js'
//请求参数
var requestParam = {
  detail: {
    REQ_HEAD: {
      SIGN: "null"
    },
    REQ_BODY: {
      goodsId: "",
    }
  },
  setCart: {
    REQ_HEAD: {
      SIGN: "null"
    },
    REQ_BODY: {
      userId: "",
      goodsId: "",
      number: ""
    }
  },
  collection: {
    REQ_HEAD: {
      SIGN: "null"
    },
    REQ_BODY: {
      userId: ""
    }
  }
}
Page({
  data: {
    modal: {
      title: "众筹说明",
      content: "在有限时间内整合众人需求，达到成交总量要求，即为众筹成功。若成功，则返回零售价差款。若失败，则按零售价安排发货，也可申请退款。不同厂商，众筹时间和总量各不相同。",
      open: false,
    },
    carCount: 0,
    itemData: {
      detail: {},
      imgDetail: []
    },
    number: 1,
    requestParam: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.loader = load.loader(that, {
      size: 50,
      borderWidth: 3
    });
    that.loader.open()
    //获取缓存购物车数量
    wx.getStorage({
      key: 'carCount',
      success: function (res) {
        that.setData({
          carCount: res.data
        })
      }
    })
    requestParam.detail.REQ_BODY.goodsId = options.id
    api.getUser({
      done: (user) => { 
    that.data.userinfo = user
    requestParam.detail.REQ_BODY.userId = user.id
    that.loadData(options)     
      },
      fail: () => {
        that.loader.close();
        that.loadData(options)
      }
    })
  },
  loadData: function (options){
    var that = this
    api.getGoodsDetail({
      method: 'POST',
      data: {
        REQ_MESSAGE: JSON.stringify(requestParam.detail)
      },
      success: (res) => {
        that.loader.close();
        console.log(res)
        var data = res.rows;
        that.data.itemData.detail = res.rows[0].goodsDetails[0];
        that.data.itemData.imgDetail = res.rows[0].queryGoodsDetailsImages;
        for (var i in that.data.itemData.imgDetail) {
          if (that.data.itemData.imgDetail[i].img_type == 1) {
            options.image = that.data.itemData.imgDetail[i].image_relative
          }
        }
        that.setData({
          itemData: that.data.itemData,
          image: options.image,
          collectionState: res.rows[0].status
        })
      },
      fail: (res) => {
        that.loader.close();
      }
    });
  },
  onShow: function () {
    var that = this
    api.getUser({
      done: (user) => {
        that.data.userinfo = user
        var jsonSrt = '{"REQ_HEAD":{"SIGN":"null"},"REQ_BODY":{"userId":"' + user.id + '"}}'
        api.setCartNumber({
          method: 'POST',
          data: {
            REQ_MESSAGE: jsonSrt
          },
          success: (res) => {
            that.setData({
              carCount: res.records || 0
            })
          }
        })
      }
    })
  },
  addToCart: function () {
    var that = this
    if (that.data.itemData.detail.inventory_amount <= 0 || !that.data.itemData.detail.inventory_amount) {
      wx.showToast({
        title: '没有库存了',
        image: '/image/ico/warning-ico.png',
        duration: 2000
      })
      return;
    }
    api.getUser({
      done: (user) => {
        that.data.userinfo = user
        that.loader.open()
        requestParam.setCart.REQ_BODY.userId = user.id.toString()
        requestParam.setCart.REQ_BODY.goodsId = that.data.itemData.detail.goodsId
        requestParam.setCart.REQ_BODY.number = that.data.number.toString()
        api.setCart({
          method: 'POST',
          data: {
            REQ_MESSAGE: JSON.stringify(requestParam.setCart)
          },
          success: (res) => {
            that.loader.close(); //关闭载入动画
            if (res.REP_BODY.RSPCOD == "000000") {
              wx.showToast({
                title: '加入成功',
                icon: 'success',
                duration: 2000
              })
              that.data.carCount += that.data.number
              that.setData({
                carCount: that.data.carCount
              })
              // wx.setStorage({
              //   key: "carCount",
              //   data: that.data.count
              // })

            } else {
              wx.showToast({
                title: '加入失败',
                image: '/image/ico/error-ico.png',
                duration: 2000
              })
            }
          },
          fail: (res) => {
            that.loader.close(); //关闭载入动画
            wx.showToast({
              title: '加入失败',
              image: '/image/ico/error-ico.png',
              duration: 2000
            })
          }
        });
      },
      fail: () => {
        wx.navigateTo({
          url: '/pages/login/login',
        })
      }
    })
  },
  makeCall: function () {
    var that=this
    var list = [that.data.itemData.detail.customer_phone ||"暂未添加"]
    wx.showActionSheet({
      itemList: list,
      itemColor: "#e30c26",
      success: function (res) {
        wx.makePhoneCall({
          phoneNumber: list[res.tapIndex]
        })
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },
  open_modal: function () {
    var that = this
    var modal = that.data.modal
    modal.open = true
    that.setData({
      modal: modal
    })
  },
  close_modal: function () {
    var that = this
    var modal = that.data.modal
    modal.open = false
    that.setData({
      modal: modal
    })
  },
  confirm_select: function () {
    this.close_modal();
  },
  setCartCount: function (e) {
    var that = this
    var selfData = e.currentTarget.dataset //当前选择
    var num = that.data.number
    if (parseInt(selfData.type)) {
      num++;
    } else {
      num--;
    }
    num = num >= selfData.max ? selfData.max : num
    that.setData({
      number: that.data.number = num ? num : 1
    })

  },
  collection: function () {
    var that = this
    api.getUser({
      done: (user) => {
        requestParam.collection.REQ_BODY = {};
        requestParam.collection.REQ_BODY.userId = user.id.toString();
        if (that.data.collectionState == 1) {
          requestParam.collection.REQ_BODY.type = "0";
          requestParam.collection.REQ_BODY.id = that.data.itemData.detail.goodsId.toString();
          var jsonStr = '{"REQ_HEAD":{"SIGN":"null"},"REQ_BODY":{"userId":"' + user.id + '","type":"0","id":"' + that.data.itemData.detail.goodsId + '" }}'
          //取消收藏
          api.delCollection({
            method: 'POST',
            data: {
              REQ_MESSAGE: jsonStr
            },
            success: (res) => {
              that.loader.close(); //关闭载入动画
              console.log(res)
              if (res.REP_BODY.RSPCOD == "000000") {
                //保存删除id
                wx.setStorage({
                  key: 'collectionMsg',
                  data: [{
                    id: that.data.itemData.detail.goodsId
                  }, {
                    id: null
                  }]
                })
                that.setData({
                  itemData: that.data.itemData,
                  collectionState: 0
                })
              } else {
                // wx.showToast({
                //   title: '加入失败',
                //   image: '/image/ico/error-ico.png',
                //   duration: 2000
                // })
              }
            },
            fail: (res) => {
              that.loader.close(); //关闭载入动画
            }
          });
        } else {
          //requestParam.collection.REQ_BODY.goodsId = that.data.itemData.detail.goodsId.toString();
          var json = '{"REQ_HEAD":{"SIGN":"null"},"REQ_BODY":{"userId":"' + user.id + '","goodsId":"' + that.data.itemData.detail.goodsId + '"}}'
          api.setCollection({
            method: 'POST',
            data: {
              REQ_MESSAGE: json
            },
            success: (res) => {
              that.loader.close(); //关闭载入动画
              console.log(res)
              if (res.REP_BODY.RSPCOD == "000000") {
                wx.removeStorage({
                  key: 'collectionMsg'
                })
                that.setData({
                  itemData: that.data.itemData,
                  collectionState: 1
                })
                wx.showToast({
                  title: '收藏成功',
                  icon: 'success',
                  duration: 2000
                })
              } else {
                wx.showToast({
                  title: '收藏失败',
                  image: '/image/ico/error-ico.png',
                  duration: 2000
                })
              }
            },
            fail: (res) => {
              that.loader.close(); //关闭载入动画
            }
          });
        }
      },
      fail: () => {
        wx.navigateTo({
          url: '/pages/login/login',
        })
      }
    })
  },
  buyNow: function () {
    if (!this.data.userinfo) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return
    }
    if (this.data.itemData.detail.inventory_amount <= 0 || !this.data.itemData.detail.inventory_amount) {
      wx.showToast({
        title: '没有库存了',
        image: '/image/ico/warning-ico.png',
        duration: 2000
      })
      return;
    }
    var goodsDetails = this.data.itemData.detail
    var orderArray = []
    var order = {}
    var orderDetail = {}
    order.vendor_name = goodsDetails.brand_name
    order.logo_url = ""
    order.vendor_id = goodsDetails.vendor_id

    orderDetail.shop_id = goodsDetails.goodsId
    orderDetail.number = this.data.number
    orderDetail.unit_price = goodsDetails.sales_price
    orderDetail.shop_name = goodsDetails.shop_name
    orderDetail.price = goodsDetails.sales_price
    orderDetail.image = this.data.image
    orderDetail.number = this.data.number
    orderDetail.shop_series = goodsDetails.shop_series
    orderDetail.crowdfundingId = "C"
    order.child = [orderDetail]
    orderArray[0] = order
    var str = JSON.stringify(orderArray);
    var encodeStr = encodeURI(encodeURI(str))
    wx.navigateTo({
      url: '/pages/order/confirmOrder/confirmOrder?order=' + encodeStr + '&sgin=1',
    })
  }
})